package com.umsoft.smart.framework.helper;

import com.umsoft.smart.framework.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Bean 助手类
 */
public final class BeanHelper {
    //定义 Bean 映射（用来存放 Bean 类与 Bean 实例的映射关系）
    private static final Map<Class<?>,Object> BEAN_MAP = new HashMap<>();

    static {
        Set<Class<?>> classSet = ClassHelper.getBeanClassSet();
        classSet.stream().forEach(cls->{
            Object obj = ReflectionUtil.newInstance(cls);
            BEAN_MAP.put(cls,obj);
        });
    }

    public static Map<Class<?>,Object> getBeanMap(){
        return BEAN_MAP;
    }

    /**
     * 获取指定 Bean
     * @param cls
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> cls){
        if(BEAN_MAP.containsKey(cls)){
            return (T) BEAN_MAP.get(cls);
        }
        throw new RuntimeException("can not get bean by class:"+cls);
    }

    /**
     * 设置 Bean 实例
     * @param cls
     * @param obj
     */
    public static void setBean(Class<?> cls,Object obj){
        BEAN_MAP.put(cls,obj);
    }
}
